package com.example.demo3.adapter;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.demo3.R;
import com.example.demo3.bean.Student;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义适配器
 */
public class CustomAdapter extends BaseAdapter {


    private List<Student> students = new ArrayList<>();

    //布局服务
    private LayoutInflater inflater;

    public CustomAdapter(List<Student> students, Context context) {
        inflater = LayoutInflater.from(context);
        this.students = students;
    }

    /**
     * 获取列表长度
     *
     * @return
     */
    @Override
    public int getCount() {
        return students.size();
    }


    /**
     * 获取列表对象
     *
     * @param i
     * @return
     */
    @Override
    public Object getItem(int i) {

        //判断数组越界
        if (i >= 0 && i < students.size()) {
            return students.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }


    /**
     * 将数据绑定到控件上
     *
     * @param i
     * @param view
     * @param viewGroup
     * @return
     */
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (null == view) {
            //为每个子项加载布局
            view = inflater.inflate(R.layout.list_item, null);
        }

        TextView nameTextView = view.findViewById(R.id.name);
        TextView ageTextView = view.findViewById(R.id.age);

        Student student = (Student) getItem(i);

        if (student != null) {
            nameTextView.setText(student.getName());

            //setText方法只能使用String类型，int数据需要转换成String
            ageTextView.setText(student.getAge() + "");
        }

        return view;
    }
}
